<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>推流页面</title>
</head>

<body>
<video id="video" style="width: 800px; height: 600px;" autoplay muted></video>
<button type="button" id="shareButton">共享屏幕</button>
<script>
  let pc, ws
  const waitWebsocketReady = (ws) => {
    return new Promise((resolve, reject) => {
      ws.onopen = () => {resolve()}
    })
  }
  const init = async () => {
    pc = new RTCPeerConnection()
    ws = new WebSocket('ws://127.0.0.1:9000')
    await waitWebsocketReady(ws)
    ws.send('publish')
    ws.addEventListener('message', (event) => {
      let msg = JSON.parse(event.data)
      console.log('ws接收', msg)
      switch (msg.type) {
        case "answer":
          pc.setRemoteDescription(msg)
          break
        default:
          pc.addIceCandidate(msg);
          break
      }
    })
    pc.addEventListener('icecandidate', (event) => {
      console.log('icecandidate', event)
      if (event.candidate) {
        ws.send(JSON.stringify(event.candidate))
      }
    })
  }
  init()
  document.getElementById('shareButton').onclick = async () => {
    let videoDom = document.getElementById("video")
    const localMediaStream = await window.navigator.mediaDevices.getDisplayMedia()
    console.log('mediaStream', localMediaStream)
    const sendMediaStream = new MediaStream()
    localMediaStream.getTracks().forEach(track =>{
      pc.addTrack(track, sendMediaStream)
    })
    videoDom.srcObject = localMediaStream
    const offer = await pc.createOffer({
      offerToReceiveVideo: true,
      offerToReceiveAudio: true,
      iceRestart: true
    })
    await pc.setLocalDescription(offer)
    ws.send(JSON.stringify(offer))
  }
</script>
</body>

</html>
